package com.bmob.lover.viewmodel.base

import com.bmob.lover.app.ext.assembly
import com.bmob.lover.app.ext.equal
import com.bmob.lover.app.ext.getTableName
import com.bmob.lover.app.util.getCurrentUser
import com.bmob.lover.data.model.bean.User
import com.bmob.lover.data.repository.BmobRepository
import com.theone.mvvm.core.base.viewmodel.BaseListViewModel
import rxhttp.wrapper.cahce.CacheMode
import rxhttp.wrapper.utils.getActualTypeParameter
import java.lang.reflect.Type


//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-04-23 09:59
 * @describe 统一的请求封装
 * @email 625805189@qq.com
 * @remark
 */
abstract class BaseListRequestViewModel<T> :
    BaseListViewModel<T>() {

    var mUser: User? = getCurrentUser()

    var mUserId: String = ""

    // 泛型类型
    var mType: Type = getActualTypeParameter(this@BaseListRequestViewModel::class.java, 0)

    // 表名
    var mTableName: String

    val isDelete = equal("isDelete", false)

    init {
        // 拿到泛型T的类名
        mTableName = mType.getTableName()
        mUser?.let {
            mUserId = it.objectId
        }
    }

    protected open fun getUrl() = "/1/classes/$mTableName"
    protected open fun bql() = ""
    protected open fun where(): String = assembly(isDelete, otherWhere())
    protected open fun otherWhere(): String = ""
    protected open fun include(): String = ""
    protected open fun keys(): String = ""
    protected open fun order(): String = "-createdAt"
    protected open fun limit(): Int = 12
    protected open fun sum(): String = ""
    protected open fun groupBy(): String = ""
    protected open fun groupCount(): Boolean = false
    protected open fun skip(): Boolean = true
    protected open fun cacheMode(): CacheMode = getCacheMode()

    override fun requestServer() {
        request({
            val response = BmobRepository.INSTANCE.requestList<T>(
                mType, getUrl(), page, getCacheMode(), bql(),
                where(), order(), include(), keys(), sum(), groupBy(), groupCount(), limit(), skip()
            )
            response?.let {
                onSuccess(it.results, it.pageInfo)
            }
        })
    }

    open fun getCacheMode(): CacheMode {
        return when {
            isFresh -> CacheMode.NETWORK_SUCCESS_WRITE_CACHE
            isFirst -> CacheMode.READ_CACHE_FAILED_REQUEST_NETWORK
            else -> CacheMode.ONLY_NETWORK
        }
    }

}
